/**
 * Created by henian.xu on 2018/11/10.
 * axios 全局拦截器
 */

import Vue from 'vue';
import Axios from 'axios';

import Config from './config';
const vm = new Vue();

/**
 * 拦截器抽象类 不可实例化
 */
class InterceptorBase {
    constructor(context) {
        this.ctx = context;
        this.$axios = context.$axios;
        this.superMethods = {};
    }
    init() {
        const { $axios, onRequest, onResponse, onError, onRequestError, onResponseError } = this;
        onRequest && $axios.onRequest(onRequest.bind(this));
        onResponse && $axios.onResponse(onResponse.bind(this));
        onError && $axios.onError(onError.bind(this));
        onRequestError && $axios.onRequestError(onRequestError.bind(this));
        onResponseError && $axios.onResponseError(onResponseError.bind(this));
        this.setConfig();
    }
    /**
     * 创建取消令牌
     */
    createCancelToken() {
        const cancelToken = Axios.CancelToken;
        return cancelToken.source();
    }
    setConfig() {
        const { $axios, superMethods } = this;
        superMethods['get'] = $axios['get'];
        superMethods['post'] = $axios['post'];
        $axios['get'] = this.get.bind(this);
        $axios['post'] = this.post.bind(this);
    }
    get(url, params = {}, cfg = {}) {
        const cancelSource = params._cancelSource || this.createCancelToken();
        cfg = {
            ...Config,
            ...cfg,
            _cancel: cancelSource.cancel,
            // 默认:false; 是否重复发送请求
            _isRepeat: params._isRepeat,
            // 默认:true; 当不可重复请求时, true:取消之前的请求; false:取消之后的请求
            _isCancelBefore: params._isCancelBefore === undefined ? true : params._isCancelBefore,
            // 默认:false; 是否自已处理错误请求，false 框架统一处理,true:框架不做任何处理
            _isHandleError: params._isHandleError,
            // 默认:true; 是否拼接 baseUrl
            _joinBaseUrl: params._joinBaseUrl === undefined ? true : params._joinBaseUrl,
        };
        delete params._isRepeat;
        delete params._isCancelBefore;
        delete params._isHandleError;
        delete params._joinBaseUrl;
        params = {
            ...params,
            _T: new Date().getTime(),
        };

        // console.log('get111111111111111111111111111111111111', params);
        return this.superMethods.get(url, {
            ...cfg,
            params,
            cancelToken: cancelSource.token,
        });
    }
    post(url, params = {}, cfg = {}) {
        const cancelSource = params._cancelSource || this.createCancelToken();
        cfg = {
            ...Config,
            ...cfg,
            _cancel: cancelSource.cancel,
            cancelToken: cancelSource.token,
            // 默认:false; 是否重复发送请求
            _isRepeat: params._isRepeat,
            // 默认:false(post的默认值与get的相反); 当不可重复请求时, true:取消之前的请求; false:取消之后的请求
            _isCancelBefore: params._isCancelBefore,
            // 默认:false; 是否自已处理错误请求，false 框架统一处理,true:框架不做任何处理
            _isHandleError: params._isHandleError,
            // 默认:true; 是否拼接 baseUrl
            _joinBaseUrl: params._joinBaseUrl === undefined ? true : params._joinBaseUrl,
        };
        delete params._isRepeat;
        delete params._isCancelBefore;
        delete params._isHandleError;
        delete params._joinBaseUrl;
        return this.superMethods.post(url, params, cfg);
    }
    // onRequest(config) {}
    // onResponse(response) {}
    onError(error) {
        const { message, response } = error;
        // 自取消
        if (message && message.code === 1) return;
        // console.error('[Axios Error]');
        const code = parseInt(response && response.status);
        if (code === 400) {
            this.ctx.redirect('/400');
        }
    }
    // onRequestError(error) {}
    // onResponseError(error) {}
}

class ServerInterceptor extends InterceptorBase {
    constructor(context) {
        super(context);
        this.init();
    }
    onRequest() {
        console.log('ServerInterceptor');
    }
}
class clientInterceptor extends InterceptorBase {
    constructor(context) {
        super(context);
        this.init();
    }
    onRequest() {
        console.log('clientInterceptor');
    }
    onResponse(response) {
        const { config, data: result } = response;
        // 接口错误提示信息全局统一拦截提示
        if (!result.success) {
            if (config._isHandleError) return Promise.resolve(response);
            vm.$messageBox.alert(result.msg, '温馨提示', {
                callback() {
                    switch (result.code) {
                        case 5001: // 订单超时
                        case 4001: // 商品已下架或不存在 无法访问商品
                        case 6001: // 订单中的商品已全部申请售后了 无法再申请售后
                            // Router.go(-1);
                            break;
                    }
                },
            });
            return Promise.reject(response);
        } else {
            return Promise.resolve(response);
        }
    }
}

export default context => {
    process.server && new ServerInterceptor(context);
    process.client && new clientInterceptor(context);
};
